package com.tff.gmall.user.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.tff.gmall.RedisUtil;
import com.tff.gmall.beans.UmsMember;
import com.tff.gmall.service.UmsMemberService;
import com.tff.gmall.user.mapper.UmsMemberMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.Jedis;

@Service
public class UmsMemberServiceImpl implements UmsMemberService {

    @Autowired
    private UmsMemberMapper umsMemberMapper;

    private RedisUtil redisUtil = new RedisUtil();

    @Override
    public UmsMember getUmsMemberById(Integer id) {
        return umsMemberMapper.getUmsMemberById(id);
    }

    @Override
    public UmsMember loginCheck(UmsMember umsMember) {
        UmsMember umsMemberFromDb = null;
        Jedis redis = null;
        try {
            redis = redisUtil.getRedis();
            if (redis != null){
                String umsMemberStr = redis.get("user:"+umsMember.getPassword()+":info");
                if (StringUtils.isNotBlank(umsMemberStr)){
                    //密码验证通过
                    UmsMember umsMemberFromCache = JSON.parseObject(umsMemberStr, UmsMember.class);
                    return umsMemberFromCache;

                }else {
                    //密码验证失败
                    //也有可能是用户数据在缓存中不存在，这时候也需要查询数据库
                    umsMemberFromDb = umsMemberMapper.loginCheckMapper(umsMember);
                    if(umsMemberFromDb != null){
                        redis.setex("user:"+umsMember.getPassword()+":info",60*60*24,JSON.toJSONString(umsMemberFromDb));
                    }
                    return umsMemberFromDb;
                }
            }else {
                //redis链接不上，也需要查询数据库
                umsMemberFromDb = umsMemberMapper.loginCheckMapper(umsMember);
                return umsMemberFromDb;
            }
        }finally {
            redis.close();
        }
    }

    @Override
    public void addUserToken(String id, String token) {
        Jedis redis = redisUtil.getRedis();
        redis.setex("user:"+id+":token",60*60*2,token);
        redis.close();
    }
}
